package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.GroupTopicCommentDao;
import jumpingnotes.model.entity.GroupTopicComment;
import net.jf.lucene.analysis.mmseg.MMSegAnalyzer;

import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.orm.hibernate3.HibernateCallback;

public class GroupTopicCommentHibernateDao extends GenericHibernateDao<GroupTopicComment> implements
		GroupTopicCommentDao
{
	public GroupTopicCommentHibernateDao()
	{
		super(GroupTopicComment.class);
	}

	@SuppressWarnings("unchecked")
	public List<GroupTopicComment> findGroupTopicCommentByGroupTopicId(final int groupTopicId, final int firstResult,
			final int maxResults)
	{
		return (List<GroupTopicComment>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct gtc from GroupTopicComment gtc where gtc.groupTopic.groupTopicId=:groupTopicId order by gtc.createTime asc");
				query.setInteger("groupTopicId", groupTopicId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public void indexGroupTopicComment()
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		List<GroupTopicComment> grouptopiccommentList = session.createCriteria(GroupTopicComment.class).list();
		for (GroupTopicComment grouptopiccomment : grouptopiccommentList)
		{
			fullTextSession.index(grouptopiccomment);
		}
	}

	@SuppressWarnings("unchecked")
	public List<GroupTopicComment> searchGroupTopicComment(String keyword, int firstResult, int maxResults)
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		try
		{
			MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[] {
				"body"
			}, new MMSegAnalyzer());
			org.apache.lucene.search.Query query = parser.parse(keyword);
			Query hibQuery = fullTextSession.createFullTextQuery(query, GroupTopicComment.class);

			if (firstResult >= 0)
				hibQuery.setFirstResult(firstResult);
			if (maxResults > 0)
				hibQuery.setMaxResults(maxResults);

			List<GroupTopicComment> result = hibQuery.list();
			return result;
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
